# ==================== 启动浏览器自动化 ====================
from playwright.sync_api import sync_playwright

from LogConfig import getLog
from UTIL import 初始化浏览器, 登录
from 表格处理 import process_excel_file
from 配置文件 import 无头模式, 用户名

logger = getLog('主程序')

科目列表 = ['2202999500', '2202999800']

区域公司字典 = {
    '测试': ["6768"],
    '江苏海上': ['6744', '6665', '6761', '6784', '6791', '6792', '6794', '6856'],
    '江苏陆上': ['6629', '6624', '6625', '6626', '6704', '6828', '6839', '6862', '6909', '6628', '6927', '6627',
                 '6943'],
    '宁夏': ['6750', '675A', '6837', '6838', '6889', '66D3', '6996', '6786', '678D', '6723', '6747'],
    '陕西': ['6680', '6916', '6938', '6950', '6972', '66C9', '6681', '6736', '6748', '6749', '6813', '6976', '6975',
             '66D0']
}

区域 = '测试'

with sync_playwright() as playwright实例:
    # 初始化浏览器
    浏览器实例, page = 初始化浏览器(playwright实例, 无头模式, 用户名)

    page = 登录(page, 用户名)

    url = "https://ceerp.chnenergy.com.cn/sap/bc/ui2/flp?sap-client=800&sap-language=ZH#FAGLB03-manage"
    page.goto(url)

    # page.pause()
    for 公司代码 in 区域公司字典.get(区域):

        # 刷新网页
        page.reload()
        page.wait_for_load_state("networkidle")
        page.wait_for_load_state("load")
        page.get_by_role("heading", name="总帐科目余额显示").wait_for()

        page.locator("#application-FAGLB03-manage").content_frame.get_by_role("textbox", name="公司代码").fill(公司代码)
        page.locator("#application-FAGLB03-manage").content_frame.get_by_role("button", name="多项选择").first.click()

        idx = 0

        # page.pause()

        page.locator("#application-FAGLB03-manage").content_frame.get_by_role("dialog",
                                                                              name="科目号 的多种选择").get_by_role(
            "textbox").fill("2202999800")

        # 使用部分匹配点击span
        page.locator("#application-FAGLB03-manage").content_frame.locator(
            "[id*='mrss-cont-none-Row-1'] span").nth(2).click()

        # 使用部分匹配填充文本框
        page.locator("#application-FAGLB03-manage").content_frame.locator(
            "[id*='mrss-cont-none-Row-1']").get_by_role("textbox").fill("2202999500")

        # page.locator("#application-FAGLB03-manage").content_frame.locator("#tbl50841-mrss-cont-none-Row-1 span").nth(
        #     2).click()
        # page.locator("#application-FAGLB03-manage").content_frame.locator("#tbl50841-mrss-cont-none-Row-1").get_by_role(
        #     "textbox").fill("2202999500")

        page.locator("#application-FAGLB03-manage").content_frame.get_by_role("button", name="复制 (F8)").click()
        page.locator("#application-FAGLB03-manage").content_frame.get_by_role("textbox", name="会计年度").fill("2025")
        page.locator("#application-FAGLB03-manage").content_frame.get_by_role("button", name="执行  加重").click()

        # page.pause()

        # 定义要定位的元素
        no_subject_element = page.locator("#application-FAGLB03-manage").content_frame.get_by_text(
            "没有科目完成选择条件", exact=True)

        try:
            # 等待元素出现，超时时间为5秒
            no_subject_element.wait_for(timeout=5000)
            logger.warning(f"「{公司代码}」在5秒内定位到「没有科目完成选择条件」元素")
            continue
        except Exception as e:
            # 如果5秒内没有找到元素，会抛出异常
            pass

        # 定义要定位的元素
        no_data_element = page.locator("#application-FAGLB03-manage").content_frame.locator("span").filter(
            has_text="不存在对会计年度 2025 的数据").nth(1)
        try:
            # 等待元素出现，超时时间为5秒
            no_data_element.wait_for(timeout=5000)
            # 如果代码执行到这里，说明元素在5秒内被找到了
            logger.warning(f"「{公司代码}」在5秒内定位到「不存在对会计年度 2025 的数据」元素")
            continue
        except Exception as e:
            # 如果5秒内没有找到元素，会抛出异常
            pass

        try:
            page.locator("#application-FAGLB03-manage").content_frame.get_by_text("总计").dblclick(timeout=30000)
        except Exception as e:
            logger.info(f"没有定位到页面“总计”元素: {e}")

        page.get_by_role("heading", name="总帐科目行项目显示 总帐视图").wait_for(timeout=30000 * 20)
        page.keyboard.press("Shift+F4")

        with page.expect_download() as download_info:
            page.locator("#application-FAGLB03-manage").content_frame.get_by_role("button", name="继续").click()
        download = download_info.value

        original_name = download.suggested_filename
        文件路径 = rf"download\{区域}\{公司代码}_{original_name}"
        download.save_as(文件路径)

        # 处理Excel文件
        template_path = "往来事务码检查导出底稿.xlsx"
        result_path = process_excel_file(公司代码, 文件路径, template_path)

        if result_path:
            logger.info("数据处理完成")
        else:
            logger.info("没有需要处理的数据")
